﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web;
using ImageResizer;


public partial class Trainings : System.Web.UI.Page
{
    ServerObject mServerObject = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        addNewTrainingDataCalendarExtender.Format = Constants.Constants.ISODateBackwardDotsFormat;

        if (mServerObject == null) mServerObject = new ServerObject();
        if (Utils.AutentificatedUser)
        {
            if (!IsPostBack)
            {
                SetInitialRowForNewClientsTable();
                FillClientFilter();

                string trainingStringID = string.Empty;
                if (Request["trid"] != null && !Request["trid"].ToString().Equals(string.Empty))
                {
                    trainingStringID = Request["trid"].ToString();
                }

                if (trainingStringID.Equals("n"))
                {
                    ClearAddNewPanel();
                    ShowPanel(addNewTrainingPanel.ID);
                }
                else
                {
                    int trainingID = 0;
                    int.TryParse(trainingStringID, out trainingID);

                    if (trainingID != 0)
                    {
                        SelectExistingTraining(trainingID);
                    }
                    else
                    {
                        ShowPanel(trainingsListPanel.ID);
                    }                    
                }
            }
        }
        else
        {
            ShowPanel(string.Empty);
        }
    }

    protected void FillClientFilter()
    {
         Credits.Module moduleCredits = Utils.ModuleCredits();

        if (moduleCredits != null)
        {
            DataTable clientsDT = moduleCredits.GetClientlist();
            clientFilter.DisplayValueField = "Client Full Name";
            clientFilter.DataValueFiled = "clientID";
            clientFilter.DataSource = clientsDT;
            clientFilter.DataBind();
        }        
    }

    private const string newGridWSTableName = "newGridWSTableName";

    private void SetInitialRowForNewClientsTable()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Surname", typeof(string)));
        dt.Columns.Add(new DataColumn("BirthDate", typeof(string)));
        dt.Columns.Add(new DataColumn("IDNP", typeof(string)));
        dt.Columns.Add(new DataColumn("TelFix", typeof(string)));
        dt.Columns.Add(new DataColumn("TelMob1", typeof(string)));
        dt.Columns.Add(new DataColumn("TelMob2", typeof(string)));
        dt.Columns.Add(new DataColumn("Email", typeof(string)));
        dt.Columns.Add(new DataColumn("Localitatea", typeof(string)));
        dt.Columns.Add(new DataColumn("Raion", typeof(string)));
        dt.Columns.Add(new DataColumn("SortGroup", typeof(string)));
        dt.Columns.Add(new DataColumn("Status", typeof(string)));
        dt.Columns.Add(new DataColumn("ClientID", typeof(string)));
        //dt.Columns.Add(new DataColumn("ClientPersonalFolder", typeof(string)));
        //dt.Columns.Add(new DataColumn("ClientPersonalPhoto", typeof(string)));
        //dt.Columns.Add(new DataColumn("ClientOnlyFile", typeof(string)));

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Name"] = string.Empty;
        dr["Surname"] = string.Empty;
        dr["BirthDate"] = string.Empty;
        dr["IDNP"] = string.Empty;
        dr["TelFix"] = string.Empty;
        dr["TelMob1"] = string.Empty;        
        dr["TelMob2"] = string.Empty;
        dr["Email"] = string.Empty;
        dr["Localitatea"] = string.Empty;
        dr["Raion"] = string.Empty;
        dr["SortGroup"] = string.Empty;
        dr["Status"] = string.Empty;
        dr["ClientID"] = string.Empty;
        //dr["ClientPersonalFolder"] = string.Empty;
        //dr["ClientPersonalPhoto"] = string.Empty;
        //dr["ClientOnlyFile"] = string.Empty;

        dt.Rows.Add(dr);
        
        //Store the DataTable in ViewState
        ViewState[newGridWSTableName] = dt;
        newClientGridView.DataSource = dt;
        newClientGridView.DataBind();
    }

    private void UpdateNewClientGridView()
    {
        if (ViewState[newGridWSTableName] != null)
        {
            DataTable dt = (DataTable)ViewState[newGridWSTableName];
            if (dt != null)
            {
                newClientGridView.DataSource = dt;
                newClientGridView.DataBind();

                int MoldovaCountrCode = 133;
                DataTable raionList = Utils.ModuleMain().GetProvinceListByCountry(MoldovaCountrCode);
                DataTable sortGrouplist = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.ClientCategories);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox nameTextBox = (TextBox)newClientGridView.Rows[i].Cells[1].FindControl("nameTextBox");
                    TextBox surnameTextBox = (TextBox)newClientGridView.Rows[i].Cells[2].FindControl("surnameTextBox");
                    TextBox birthDateTextBox = (TextBox)newClientGridView.Rows[i].Cells[3].FindControl("birthDateTextBox");
                    TextBox codPersonalTextBox = (TextBox)newClientGridView.Rows[i].Cells[4].FindControl("codPersonalTextBox");
                    TextBox telFixTextBox = (TextBox)newClientGridView.Rows[i].Cells[5].FindControl("telFixTextBox");
                    TextBox telMobil1TextBox = (TextBox)newClientGridView.Rows[i].Cells[6].FindControl("telMobil1TextBox");
                    TextBox emailTextBox = (TextBox)newClientGridView.Rows[i].Cells[7].FindControl("emailTextBox");
                    TextBox localitateaTextBox = (TextBox)newClientGridView.Rows[i].Cells[8].FindControl("localitateaTextBox");
                    DropDownList raionDDL = (DropDownList)newClientGridView.Rows[i].Cells[9].FindControl("raionDDL");
                    DropDownList sortGroupDDL = (DropDownList)newClientGridView.Rows[i].Cells[10].FindControl("sortGroupDDL");
                    Image statusImage = (Image)newClientGridView.Rows[i].Cells[11].FindControl("statusImage");
                    //Image clientPersonalPhoto = (Image)newClientGridView.Rows[i].Cells[15].FindControl("personalFotoImage");

                    nameTextBox.Text = dt.Rows[i]["Name"].ToString();
                    surnameTextBox.Text = dt.Rows[i]["Surname"].ToString();
                    birthDateTextBox.Text = dt.Rows[i]["BirthDate"].ToString();
                    codPersonalTextBox.Text = dt.Rows[i]["IDNP"].ToString();
                    telFixTextBox.Text = dt.Rows[i]["TelFix"].ToString();
                    telMobil1TextBox.Text = dt.Rows[i]["TelMob1"].ToString();
                    emailTextBox.Text = dt.Rows[i]["Email"].ToString();
                    localitateaTextBox.Text = dt.Rows[i]["Localitatea"].ToString();
                    //clientPersonalPhoto.ImageUrl = dt.Rows[i]["ClientPersonalPhoto"].ToString();

                    try
                    {
                        Utils.FillSelector(raionDDL, raionList, "Name", "Code");
                        raionDDL.SelectedValue = dt.Rows[i]["Raion"].ToString();
                    }
                    catch { }

                    try
                    {
                        Utils.FillSelector(sortGroupDDL, sortGrouplist, "Name", "Code");
                        sortGroupDDL.SelectedValue = dt.Rows[i]["SortGroup"].ToString();
                    }
                    catch { }


                    string statusInfo = dt.Rows[i]["Status"].ToString();
                    switch (statusInfo)
                    {
                        case "Ok":
                            statusImage.ImageUrl = "~/App_Images/ok.png";
                            statusImage.ToolTip = "Ok";
                            break;

                        case "Din DB":
                            statusImage.ImageUrl = "~/App_Images/checkpoint.png";
                            statusImage.ToolTip = "Din DB";
                            break;

                        case "Duplicate":
                            statusImage.ImageUrl = "~/App_Images/attention.png";
                            statusImage.ToolTip = "Atentie!, in baza de date s-a gasit un client cu date asemanatoare!";
                            break;

                        default:
                            statusImage.ImageUrl = "~/App_Images/attention.png";
                            statusImage.ToolTip = statusInfo;
                            break;
                    }
                }
            }
        }
    }

    private void AddNewRowToGrid(int clientID)
    {
        if (ViewState[newGridWSTableName] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState[newGridWSTableName];

            if (dtCurrentTable != null)
            {
                #region Memorizam Ultimele schimbari
                for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
                {
                    TextBox nameTextBox = (TextBox)newClientGridView.Rows[i].Cells[1].FindControl("nameTextBox");
                    TextBox surnameTextBox = (TextBox)newClientGridView.Rows[i].Cells[2].FindControl("surnameTextBox");
                    TextBox birthDateTextBox = (TextBox)newClientGridView.Rows[i].Cells[3].FindControl("birthDateTextBox");
                    TextBox codPersonalTextBox = (TextBox)newClientGridView.Rows[i].Cells[4].FindControl("codPersonalTextBox");
                    TextBox telFixTextBox = (TextBox)newClientGridView.Rows[i].Cells[5].FindControl("telFixTextBox");
                    TextBox telMobil1TextBox = (TextBox)newClientGridView.Rows[i].Cells[6].FindControl("telMobil1TextBox");
                    TextBox emailTextBox = (TextBox)newClientGridView.Rows[i].Cells[7].FindControl("emailTextBox");

                    TextBox localitateaTextBox = (TextBox)newClientGridView.Rows[i].Cells[8].FindControl("localitateaTextBox");
                    DropDownList raionDDL = (DropDownList)newClientGridView.Rows[i].Cells[9].FindControl("raionDDL");
                    DropDownList sortGroupDDL = (DropDownList)newClientGridView.Rows[i].Cells[9].FindControl("sortGroupDDL");

                    //string clientPersonalFolder = newClientGridView.Rows[i].Cells[12].Text;
                    //Image clientPersonalPhoto = (Image)newClientGridView.Rows[i].Cells[14].FindControl("personalFotoImage");
                    //string telefonMobil2 = newClientGridView.Rows[i].Cells[16].Text;
                    //string ClientOnlyFile = newClientGridView.Rows[i].Cells[17].Text;

                    dtCurrentTable.Rows[i]["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i]["Name"] = nameTextBox.Text;
                    dtCurrentTable.Rows[i]["Surname"] = surnameTextBox.Text;
                    dtCurrentTable.Rows[i]["BirthDate"] = birthDateTextBox.Text;
                    dtCurrentTable.Rows[i]["IDNP"] = codPersonalTextBox.Text;
                    dtCurrentTable.Rows[i]["TelFix"] = telFixTextBox.Text;
                    dtCurrentTable.Rows[i]["TelMob1"] = telMobil1TextBox.Text;
                    dtCurrentTable.Rows[i]["Email"] = emailTextBox.Text;
                    dtCurrentTable.Rows[i]["Localitatea"] = localitateaTextBox.Text;
                    dtCurrentTable.Rows[i]["Raion"] = raionDDL.SelectedValue;
                    dtCurrentTable.Rows[i]["SortGroup"] = sortGroupDDL.SelectedValue;
                    //dtCurrentTable.Rows[i]["ClientPersonalFolder"] = clientPersonalFolder;
                    //dtCurrentTable.Rows[i]["ClientPersonalPhoto"] = clientPersonalPhoto.ImageUrl;
                    //dtCurrentTable.Rows[i]["TelMob2"] = telefonMobil2;
                    //dtCurrentTable.Rows[i]["ClientOnlyFile"] = ClientOnlyFile;

                    if (!dtCurrentTable.Rows[i]["Status"].ToString().Equals("Din DB"))
                    {
                        if (!Utils.ModuleCredits().CheckExistClient(nameTextBox.Text, surnameTextBox.Text, Crypt.Utils.ToDateTime(birthDateTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat)))
                        {
                            dtCurrentTable.Rows[i]["Status"] = "Ok";
                        }
                        else
                        {
                            dtCurrentTable.Rows[i]["Status"] = "Duplicate";
                        }
                    }
                }
                #endregion Memorizam Ultimele schimbari

                dtCurrentTable.Rows.Add();
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["RowNumber"] = dtCurrentTable.Rows.Count;

                if (clientID != 0)
                {
                    Credits.DataObjects.Client clientObject = Utils.ModuleCredits().GetCleintObjectByID(clientID);

                    if (clientObject != null && clientObject.ClientID != 0)
                    {
                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Name"] = clientObject.FirstName;
                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Surname"] = clientObject.LastName;
                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["IDNP"] = clientObject.PersonalID;

                        if (clientObject.BirthDate != DateTime.MinValue)
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["BirthDate"] = clientObject.BirthDate.ToString( Constants.Constants.ISODateBackwardDotsFormat);

                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["TelFix"] = clientObject.TelefonFix;
                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["TelMob1"] = clientObject.TelefonMobil;
                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Email"] = clientObject.Email;

                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Localitatea"] = clientObject.Viza_Localitatea;
                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Raion"] = clientObject.Viza_Raion.ToString();
                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["SortGroup"] = clientObject.SortGroup.ToString();

                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Status"] = "Din DB";
                        dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["ClientID"] = clientID.ToString();
                        //dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["ClientPersonalFolder"] = clientObject.ClientPersonalFolder;
                        //dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["ClientPersonalPhoto"] = Utils.ModuleCredits().RootModuleFolder + "/" + clientObject.ImageURL;
                        //dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["ClientOnlyFile"] = clientObject.ImageURL;
                        //dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["TelMob2"] = clientObject.TelefonMobil2;                                            
                    }
                }        
                
                ViewState[newGridWSTableName] = dtCurrentTable;
            }    
        }

        else
        {
            Response.Write("ViewState is null");
        }

        UpdateNewClientGridView();
    }
       
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid(0);
    }

    protected void newClientGridView_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        int deletedIndex = e.RowIndex;

        if (ViewState[newGridWSTableName] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState[newGridWSTableName];

            if (dtCurrentTable != null)
            {
                #region Memorizam Ultimele schimbari 

                for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
                {
                    TextBox nameTextBox = (TextBox)newClientGridView.Rows[i].Cells[1].FindControl("nameTextBox");
                    TextBox surnameTextBox = (TextBox)newClientGridView.Rows[i].Cells[2].FindControl("surnameTextBox");
                    TextBox birthDateTextBox = (TextBox)newClientGridView.Rows[i].Cells[3].FindControl("birthDateTextBox");
                    TextBox codPersonalTextBox = (TextBox)newClientGridView.Rows[i].Cells[4].FindControl("codPersonalTextBox");
                    TextBox telFixTextBox = (TextBox)newClientGridView.Rows[i].Cells[5].FindControl("telFixTextBox");
                    TextBox telMobil1TextBox = (TextBox)newClientGridView.Rows[i].Cells[6].FindControl("telMobil1TextBox");
                    TextBox emailTextBox = (TextBox)newClientGridView.Rows[i].Cells[7].FindControl("emailTextBox");

                    TextBox localitateaTextBox = (TextBox)newClientGridView.Rows[i].Cells[8].FindControl("localitateaTextBox");
                    DropDownList raionDDL = (DropDownList)newClientGridView.Rows[i].Cells[9].FindControl("raionDDL");
                    DropDownList sortGroupDDL = (DropDownList)newClientGridView.Rows[i].Cells[10].FindControl("sortGroupDDL");

                    //string clientPersonalFolder = newClientGridView.Rows[i].Cells[12].Text;
                    //Image clientPersonalPhoto = (Image)newClientGridView.Rows[i].Cells[14].FindControl("personalFotoImage");
                    //string telefonMobil2 = newClientGridView.Rows[i].Cells[16].Text;
                    //string ClientOnlyFile = newClientGridView.Rows[i].Cells[17].Text;

                    dtCurrentTable.Rows[i]["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i]["Name"] = nameTextBox.Text;
                    dtCurrentTable.Rows[i]["Surname"] = surnameTextBox.Text;
                    dtCurrentTable.Rows[i]["BirthDate"] = birthDateTextBox.Text;
                    dtCurrentTable.Rows[i]["IDNP"] = codPersonalTextBox.Text;
                    dtCurrentTable.Rows[i]["TelFix"] = telFixTextBox.Text;
                    dtCurrentTable.Rows[i]["TelMob1"] = telMobil1TextBox.Text;
                    dtCurrentTable.Rows[i]["Email"] = emailTextBox.Text;
                    dtCurrentTable.Rows[i]["Localitatea"] = localitateaTextBox.Text;
                    dtCurrentTable.Rows[i]["Raion"] = raionDDL.SelectedValue;
                    dtCurrentTable.Rows[i]["SortGroup"] = sortGroupDDL.SelectedValue;
                    //dtCurrentTable.Rows[i]["ClientPersonalFolder"] = clientPersonalFolder;
                    //dtCurrentTable.Rows[i]["ClientPersonalPhoto"] = clientPersonalPhoto.ImageUrl;
                    //dtCurrentTable.Rows[i]["TelMob2"] = telefonMobil2;
                    //dtCurrentTable.Rows[i]["ClientOnlyFile"] = ClientOnlyFile;

                    if (!dtCurrentTable.Rows[i]["Status"].ToString().Equals("Din DB"))
                    {
                        if (!Utils.ModuleCredits().CheckExistClient(nameTextBox.Text, surnameTextBox.Text, Crypt.Utils.ToDateTime(birthDateTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat)))
                        {
                            dtCurrentTable.Rows[i]["Status"] = "Ok";
                        }
                        else
                        {
                            dtCurrentTable.Rows[i]["Status"] = "Duplicate";
                        }
                    }
                }
                #endregion Memorizam Ultimele schimbari
                
                dtCurrentTable.Rows[deletedIndex].Delete();
                dtCurrentTable.AcceptChanges();
            }
        }
       
        UpdateNewClientGridView();
    }

    protected void ClientSelecetd_Event(object sender, FilterWindow.FilterWindowEventsArg e)
    {
        List<string> selectedClientList = e.SelectedItems;
        if (selectedClientList != null && selectedClientList.Count == 1)
        {
            int clientID = 0;
            int.TryParse(selectedClientList[0], out clientID); 
            AddNewRowToGrid(clientID);
        }
    }
  

	private void FillTrainingsGridView()
	{
        int trainingID = 0; /// select all records!
        DataTable trainigsList = Utils.ModuleCredits().GetTrainingList(trainingID);
        trainingsGridView.DataSource = trainigsList;
		trainingsGridView.DataBind();	
	}
	
    private void ShowPanel(string panelName)
    {
        #region Hide panels

        emptyPanel.Visible = false;
        trainingsListPanel.Visible = false;

        addNewTrainingPanel.Visible = false;
        #endregion Hide panels

        try
        {
            #region Get Panel Name

            switch (panelName)
            {
                case "trainingsListPanel":
                    trainingsListPanel.Visible = true;
					FillTrainingsGridView();
                    break;

                case "addNewTrainingPanel":
                    addNewTrainingPanel.Visible = true;
                    {
                        SetInitialRowForNewClientsTable();
                        UpdateNewClientGridView();
                        FillClientFilter();

                        DataTable operatorsLIst = Utils.ModuleCredits().GetOperatorsList();
                        Utils.FillSelector(conducatorulDDL, operatorsLIst, "Operator Full Name", "OperatorID");

                        DataTable tipAfacere = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.TipDeInstruire);
                        Utils.FillSelector(addNewTrainingTipInstruireDDL, tipAfacere, "Name", "Code");                    
                    }

                    break;             

                case "emptyPanel":
                    emptyPanel.Visible = true;
                    break;

                default:
                    emptyPanel.Visible = true;
                    break;
            }

            #endregion Get Panel Name
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    protected void trainingsGridView_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
    {
        trainingsGridView.PageIndex = e.NewPageIndex;
		FillTrainingsGridView();
    }

    protected void trainingsGridView_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

            for (int i = 0; i < e.Row.Cells.Count - 1; i++)
            {
                e.Row.Cells[i].Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.trainingsGridView, "Select$" + e.Row.RowIndex);
            }
        }
    }

    protected void trainingsGridView_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        int trainingID = 0;
        int index = e.RowIndex;
        int.TryParse(trainingsGridView.Rows[index].Cells[0].Text, out trainingID);

        if (Utils.ModuleCredits().DeleteTraining(trainingID))
        {
            ShowPanel(trainingsListPanel.ID);
        }
        else
        {
            Utils.InfoText(this, "Atentie", "Datele nu au fost sterse. Verificati conectiunea cu internet");
        }
    }
   
    private void SelectExistingTraining(int trainigID)
    {
        ClearAddNewPanel();
        ShowPanel(addNewTrainingPanel.ID);
        trainingOperationHiddenField.Value = "Edit";

        editTrainingIDHiddenField.Value = trainigID.ToString();

        DataTable trainingInfo = Utils.ModuleCredits().GetTrainingList(trainigID);

        if (trainingInfo != null && trainingInfo.Rows.Count == 1 )
        {
            if (trainingInfo.Rows[0]["trainingDate"] != System.DBNull.Value)
            {
                addNewTrainingDataTextBox.Text = ((DateTime)trainingInfo.Rows[0]["trainingDate"]).ToString( Constants.Constants.ISODateBackwardDotsFormat);
            }

            if (trainingInfo.Rows[0]["tipulInstruirii_ID"] != System.DBNull.Value)
            {
                addNewTrainingTipInstruireDDL.SelectedValue = trainingInfo.Rows[0]["tipulInstruirii_ID"].ToString();
            }

            addNewTrainingDescriereIntruireTextBox.Text = trainingInfo.Rows[0]["DescrirereaInstruirii"].ToString();
            addNewTrainingNameTextBox.Text = trainingInfo.Rows[0]["trainingName"].ToString();
            addNewTraingScopeTextBox.Text = trainingInfo.Rows[0]["trainingScop"].ToString();

            trainingPhotoImage.ImageUrl = trainingInfo.Rows[0]["trainingPhoto"].ToString();    

            DataTable trainersList = Utils.ModuleCredits().GetTrainingOperatorsListByTrainingID(trainigID);
            if (trainersList != null && trainersList.Rows.Count == 1)
            {
                conducatorulDDL.SelectedValue = trainersList.Rows[0]["OperatorID"].ToString();
            }

            DataTable clientsList = Utils.ModuleCredits().GetClientsListByTrainingID(trainigID);
            if (clientsList != null && clientsList.Rows.Count > 0 && ViewState[newGridWSTableName] != null)
            {
                DataTable dtCurrentTable = ((DataTable)ViewState[newGridWSTableName]).Clone();

                for (int i = 0; i < clientsList.Rows.Count; i++)
                {
                    if (clientsList.Rows[i]["ClientID"] != System.DBNull.Value)
                    {
                        int clientID = (int)clientsList.Rows[i]["ClientID"];

                        Credits.DataObjects.Client clientObject = Utils.ModuleCredits().GetCleintObjectByID(clientID);
                        if (clientObject != null && clientObject.ClientID != 0)
                        {
                            dtCurrentTable.Rows.Add();
                            
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["RowNumber"] = dtCurrentTable.Rows.Count;
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Name"] = clientObject.FirstName;
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Surname"] = clientObject.LastName;
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["IDNP"] = clientObject.PersonalID;

                            if (clientObject.BirthDate != DateTime.MinValue)
                                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["BirthDate"] = clientObject.BirthDate.ToString( Constants.Constants.ISODateBackwardDotsFormat);

                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["TelFix"] = clientObject.TelefonFix;
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["TelMob1"] = clientObject.TelefonMobil;
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["TelMob2"] = clientObject.TelefonMobil2;
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Email"] = clientObject.Email;
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Localitatea"] = clientObject.Viza_Localitatea;
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Raion"] = clientObject.Viza_Raion.ToString();
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["SortGroup"] = clientObject.SortGroup.ToString();
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Status"] = "Din DB";
                            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["ClientID"] = clientID.ToString();

                            //dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["ClientPersonalFolder"] = clientObject.ClientPersonalFolder;
                            //dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["ClientPersonalPhoto"] = Utils.ModuleCredits().RootModuleFolder + "/" + clientObject.ImageURL;
                            //dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["ClientOnlyFile"] = clientObject.ImageURL;                            
                        }
                    }
                }

                ViewState[newGridWSTableName] = dtCurrentTable;               
            }
        }

        UpdateNewClientGridView();
    }

    protected void trainingsGridView_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = trainingsGridView.SelectedRow;

        int trainigID = 0;
        int.TryParse(row.Cells[0].Text, out trainigID);

        SelectExistingTraining(trainigID);
    }

    protected void ClearAddNewPanel()
    {
        addNewTrainingDataTextBox.Text = string.Empty;
        addNewTrainingNameTextBox.Text = string.Empty;
        conducatorulDDL.SelectedIndex = -1;
        addNewTrainingTipInstruireDDL.SelectedIndex = -1;
        addNewTrainingDescriereIntruireTextBox.Text = string.Empty;
        addNewTraingScopeTextBox.Text = string.Empty;
    }

    protected void addNewTrainingButton_Click(object sender, EventArgs e)
    {
        ClearAddNewPanel();
        ShowPanel(addNewTrainingPanel.ID);
    }

    protected void addNewTrainingSaveButton_Click(object sender, EventArgs e)
    {
        int trainingID = 0;
        int.TryParse(editTrainingIDHiddenField.Value, out trainingID);

        int idIperator = 0;
        int.TryParse(conducatorulDDL.SelectedValue, out idIperator);

        List<int> selectedOperators = new List<int>();
        selectedOperators.Add(idIperator);
        
        List<int> selectedClients = new List<int>();

        DateTime dataInstruirii = Crypt.Utils.ToDateTime(addNewTrainingDataTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);

        int tipulInstruirii = 0;
        int.TryParse(addNewTrainingTipInstruireDDL.SelectedValue.ToString(), out tipulInstruirii);

        string descriere = addNewTrainingDescriereIntruireTextBox.Text;

        if (newClientGridView != null && newClientGridView.Rows.Count > 0)
        {
            for (int i = 0; i < newClientGridView.Rows.Count; i++)
            {
                Label clientIDLabel = (Label)newClientGridView.Rows[i].Cells[11].FindControl("clientIDLabel");
                string stringClientID = clientIDLabel.Text;

                TextBox nameTextBox = (TextBox)newClientGridView.Rows[i].Cells[1].FindControl("nameTextBox");
                string clientName = nameTextBox.Text;

                TextBox lastNameTextBox = (TextBox)newClientGridView.Rows[i].Cells[2].FindControl("surnameTextBox");
                string clientLstName = lastNameTextBox.Text;

                TextBox birthDateTextBox = (TextBox)newClientGridView.Rows[i].Cells[3].FindControl("birthDateTextBox");
                DateTime clientBirthDate = Crypt.Utils.ToDateTime(birthDateTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);

                TextBox codPersonalTextBox = (TextBox)newClientGridView.Rows[i].Cells[4].FindControl("codPersonalTextBox");
                string personalID = codPersonalTextBox.Text;

                TextBox telFixTextBox = (TextBox)newClientGridView.Rows[i].Cells[5].FindControl("telFixTextBox");
                string telFix = telFixTextBox.Text;
                                
                TextBox telMobil1TextBox = (TextBox)newClientGridView.Rows[i].Cells[6].FindControl("telMobil1TextBox");
                string telMob1 = telMobil1TextBox.Text;

                TextBox emailTextBox = (TextBox)newClientGridView.Rows[i].Cells[7].FindControl("emailTextBox");
                string email = emailTextBox.Text;

                TextBox localitateaTextBox = (TextBox)newClientGridView.Rows[i].Cells[8].FindControl("localitateaTextBox");
                string vizaLocalitatea = localitateaTextBox.Text;

                DropDownList vizaraionDDL = (DropDownList)newClientGridView.Rows[i].Cells[9].FindControl("raionDDL");
                int vizaRaion = 0;
                int.TryParse(vizaraionDDL.SelectedValue, out vizaRaion);

                DropDownList sortGroupDDL = (DropDownList)newClientGridView.Rows[i].Cells[10].FindControl("sortGroupDDL");
                int sortGroup = 0;
                int.TryParse(sortGroupDDL.SelectedValue, out sortGroup);

                //Label clientPersonalFolderLabel = (Label)newClientGridView.Rows[i].Cells[13].FindControl("clientPersonalFolderLabel");
                //string clientPersonalFolder = clientPersonalFolderLabel.Text;

                //Label TelMob2Label = (Label)newClientGridView.Rows[i].Cells[17].FindControl("TelMob2Label");
                //string telMob2 = TelMob2Label.Text;

                //Label ClientOnlyFileLabel = (Label)newClientGridView.Rows[i].Cells[18].FindControl("ClientOnlyFileLabel");
                //string clientPersonalFotolink = ClientOnlyFileLabel.Text;

                int insertedClientID = 0;
                Image statusImage = (Image)newClientGridView.Rows[i].Cells[11].FindControl("statusImage");

                string status = statusImage.ToolTip;              

                if (!status.Equals("Din DB"))
                {
                    if (!Utils.ModuleCredits().CheckExistClient(clientName, clientLstName, clientBirthDate)
                       && Utils.ModuleCredits().AddNewClient(clientName, clientLstName, clientBirthDate, telFix, telMob1, email, sortGroup, out insertedClientID))
                        selectedClients.Add(insertedClientID);
                }
                else
                {   
                    int clientID = 0;
                    int.TryParse(stringClientID, out clientID);
                    if (clientID != 0) 
                    {
                        //Utils.ModuleCredits().UpdateClientMainData(clientID, clientName, clientLstName, clientBirthDate, telFix, telMob1, telMob2, clientPersonalFotolink, email, clientPersonalFolder);
                        //Utils.ModuleCredits().UpdateClientAddressData(clientID, 0, vizaRaion, string.Empty, vizaLocalitatea, string.Empty, 0, 0, string.Empty, string.Empty, string.Empty, false);
                        //Utils.ModuleCredits().UpdateClientPersonalData(clientID, string.Empty, personalID, DateTime.MinValue, string.Empty, 0, 0, 0, 0, 0, 0, 0, 0, 0, string.Empty, string.Empty, string.Empty, false);

                        selectedClients.Add(clientID);
                    }
                }
            } 
        }

        string trainingName = addNewTrainingNameTextBox.Text;
        string trainingScope = addNewTraingScopeTextBox.Text;
        string imageTrainingFotoLink = trainingPhotoImage.ImageUrl;

        bool resultOperation = false;

        if (trainingOperationHiddenField.Value.Equals("Edit"))
        {
            resultOperation = Utils.ModuleCredits().UpdateTraining(trainingID, dataInstruirii, selectedOperators, tipulInstruirii, selectedClients, descriere, trainingName, trainingScope, imageTrainingFotoLink);
        }
        else
        {
            resultOperation = Utils.ModuleCredits().AddNewTraining(dataInstruirii, selectedOperators, tipulInstruirii, selectedClients, descriere, trainingName, trainingScope, imageTrainingFotoLink);
        }

        if (!resultOperation)        
        {
            Utils.InfoText(this, "Atentie", "Datele nu au fost salvate. Verificati corectitudinea datelor introduse sau verificati conectiunea cu internet");
        }
    }

    protected void addNewTrainingCancelButton_Click(object sender, EventArgs e)
    {
        ShowPanel(trainingsListPanel.ID);
    }

    protected void addNewTrainingBackButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        ShowPanel(trainingsListPanel.ID);
    }
   
    //protected void newClientGridView_RowEditing(object sender, GridViewEditEventArgs e)
    //{
    //    int index = e.NewEditIndex;

    //    try
    //    {
    //        TextBox birthDateTextBox = (TextBox)newClientGridView.Rows[index].Cells[3].FindControl("birthDateTextBox");
    //        TextBox clientFirstNameTextBox = (TextBox)newClientGridView.Rows[index].Cells[1].FindControl("nameTextBox");
    //        TextBox clientLastNameTextBox = (TextBox)newClientGridView.Rows[index].Cells[2].FindControl("surnameTextBox");
    //        TextBox codPersonalTextBox = (TextBox)newClientGridView.Rows[index].Cells[4].FindControl("codPersonalTextBox");
    //        TextBox telFixTextBox = (TextBox)newClientGridView.Rows[index].Cells[5].FindControl("telFixTextBox");
    //        TextBox telMobil1TextBox = (TextBox)newClientGridView.Rows[index].Cells[6].FindControl("telMobil1TextBox");
    //        TextBox emailTextBox = (TextBox)newClientGridView.Rows[index].Cells[7].FindControl("emailTextBox");
    //        TextBox localitateaTextBox = (TextBox)newClientGridView.Rows[index].Cells[8].FindControl("localitateaTextBox");
    //        DropDownList raionDDL = (DropDownList)newClientGridView.Rows[index].Cells[9].FindControl("raionDDL");
    //        DropDownList sortGroupDDL = (DropDownList)newClientGridView.Rows[index].Cells[10].FindControl("sortGroupDDL");          

    //        Label clientIDLabel = (Label)newClientGridView.Rows[index].Cells[12].FindControl("clientIDLabel");
    //        string clientID = clientIDLabel.Text;

    //        Label clientPersonalFolderLabel = (Label)newClientGridView.Rows[index].Cells[13].FindControl("clientPersonalFolderLabel");
    //        string clientPersonalFolder = clientPersonalFolderLabel.Text;

    //        Image personalPfotoClient = (Image)newClientGridView.Rows[index].Cells[14].FindControl("personalFotoImage");
    //        FileUpload personalPhotoFileUpload = (FileUpload)newClientGridView.Rows[index].Cells[15].FindControl("personalPhotoFileUpload");

    //        Label TelMob2Label = (Label)newClientGridView.Rows[index].Cells[17].FindControl("TelMob2Label");
    //        string telefonMobil2 = TelMob2Label.Text;

    //        Label ClientOnlyFileLabel = (Label)newClientGridView.Rows[index].Cells[18].FindControl("ClientOnlyFileLabel");
    //        string clientOlyFileLink = ClientOnlyFileLabel.Text;

    //        if (birthDateTextBox != null)
    //        {
    //            string statusMessage = string.Empty;

    //            if (!birthDateTextBox.Text.Equals(string.Empty) && !birthDateTextBox.Text.Equals("&nbsp;"))
    //            {
    //                string creditModuleFileDirectory = Utils.ModuleCredits().RootModuleFolder;

    //                if (string.IsNullOrEmpty(clientID) || clientID.Equals("&nbsp;"))
    //                {
    //                    int insertedClientID = 0;

    //                    int sortGorup = 0;
    //                    int.TryParse(sortGroupDDL.SelectedValue, out sortGorup);

    //                    if (!Utils.ModuleCredits().CheckExistClient(clientFirstNameTextBox.Text, clientLastNameTextBox.Text, Crypt.Utils.ConvertStringDateToDateTime(birthDateTextBox.Text)) &&
    //                        Utils.ModuleCredits().AddNewClient(clientFirstNameTextBox.Text, clientLastNameTextBox.Text, Crypt.Utils.ConvertStringDateToDateTime(birthDateTextBox.Text), telFixTextBox.Text, telMobil1TextBox.Text, string.Empty, string.Empty, emailTextBox.Text, sortGorup, out insertedClientID) && insertedClientID != 0)
    //                    {
    //                        Credits.DataObjects.Client clientObject = Utils.ModuleCredits().GetCleintObjectByID(insertedClientID);
    //                        clientPersonalFolder = clientObject.ClientPersonalFolder;  
    //                        clientID = insertedClientID.ToString();
    //                        FillClientFilter();
    //                    }
    //                    else
    //                    {
    //                        statusMessage = "Duplicate";
    //                        clientOlyFileLink = string.Empty;                           
    //                    }
    //                }

    //                //if ((string.IsNullOrEmpty(clientPersonalFolder) || clientPersonalFolder.Equals("&nbsp;")) && !string.IsNullOrEmpty(clientID) && !clientID.Equals("&nbsp;"))
    //                //{
    //                //    int intClientID =0;
    //                //    int.TryParse(clientID, out intClientID);

    //                //    if(intClientID != 0)
    //                //    {                            
    //                //        //if (Utils.ModuleCredits().UpdateClientMainData(intClientID, clientFirstNameTextBox.Text, clientLastNameTextBox.Text, Crypt.Utils.ConvertStringDateToDateTime(birthDateTextBox.Text), telFixTextBox.Text, telMobil1TextBox.Text, telefonMobil2, clientOlyFileLink, emailTextBox.Text, creditModuleFileDirectory))
    //                //        //{
    //                //        //    clientPersonalFolder = newPersonalFolder;
    //                //        //}
    //                //    }
    //                //}

    //                if (!clientPersonalFolder.Equals(string.Empty) && !clientPersonalFolder.Equals("&nbsp;") && !string.IsNullOrEmpty(clientID) && !clientID.Equals("&nbsp;") && personalPfotoClient != null && personalPhotoFileUpload != null)
    //                {
    //                    HttpPostedFile file = personalPhotoFileUpload.PostedFile;
    //                    if (file != null && file.ContentLength >= 0)
    //                    {
    //                        Dictionary<string, string> versions = new Dictionary<string, string>();
    //                        //Define the version to generate
    //                        versions.Add("_thumb", "width=250&height=250&format=jpg&mode=max");

    //                        ImageJob im = new ImageJob(file, creditModuleFileDirectory + "\\" + clientPersonalFolder + "\\<guid>.<ext>", new ResizeSettings(versions["_thumb"]));
    //                        im.CreateParentDirectory = true; //Auto-create the uploads directory.
    //                        im.Build();

    //                        string[] fullPath = im.FinalPath.Split('\\');

    //                        string finalSmallFullFileName = string.Empty;
    //                        if (fullPath != null && fullPath.Length > 1)
    //                        {
    //                            finalSmallFullFileName = clientPersonalFolder + "/" + fullPath[fullPath.Length - 1];
    //                        }

    //                        personalPfotoClient.ImageUrl = creditModuleFileDirectory + "/" + finalSmallFullFileName;
    //                        clientOlyFileLink = finalSmallFullFileName;
    //                        statusMessage = "Din DB";
    //                    }
    //                }
    //            }
    //            else
    //            {
    //                statusMessage = "Atentie, Cimpul cu Data de nastere nu poate fi gol. Va rog introduceti data de nastere!";
    //            }

                
    //            if (ViewState[newGridWSTableName] != null)
    //            {
    //                DataTable dtCurrentTable = (DataTable)ViewState[newGridWSTableName];

    //                if (dtCurrentTable != null)
    //                {
    //                    dtCurrentTable.Rows[index]["RowNumber"] = index + 1;
    //                    dtCurrentTable.Rows[index]["Name"] = clientFirstNameTextBox.Text;
    //                    dtCurrentTable.Rows[index]["Surname"] = clientLastNameTextBox.Text;
    //                    dtCurrentTable.Rows[index]["BirthDate"] = birthDateTextBox.Text;
    //                    dtCurrentTable.Rows[index]["IDNP"] = codPersonalTextBox.Text;
    //                    dtCurrentTable.Rows[index]["TelFix"] = telFixTextBox.Text;
    //                    dtCurrentTable.Rows[index]["TelMob1"] = telMobil1TextBox.Text;
    //                    dtCurrentTable.Rows[index]["Email"] = emailTextBox.Text;
    //                    dtCurrentTable.Rows[index]["Localitatea"] = localitateaTextBox.Text;
    //                    dtCurrentTable.Rows[index]["Raion"] = raionDDL.SelectedValue;
    //                    dtCurrentTable.Rows[index]["ClientPersonalFolder"] = clientPersonalFolder;
    //                    dtCurrentTable.Rows[index]["ClientPersonalPhoto"] = personalPfotoClient.ImageUrl;
    //                    dtCurrentTable.Rows[index]["ClientOnlyFile"] = clientOlyFileLink;
    //                    dtCurrentTable.Rows[index]["TelMob2"] = telefonMobil2;
    //                    dtCurrentTable.Rows[index]["Status"] = statusMessage;

    //                    ViewState[newGridWSTableName] = dtCurrentTable;
    //                }
    //            }
    //        }
    //    }
    //    catch
    //    { }

    //    newClientGridView.EditIndex = -1;
    //    UpdateNewClientGridView();
    //}
    
    protected void trainingPhotoUploadButton_Click(object sender, EventArgs e)
    {
        HttpPostedFile file = trainingPhotoFileUpload.PostedFile;

        if (file != null && file.ContentLength >= 0)
        {
            Dictionary<string, string> versions = new Dictionary<string, string>();
            //Define the version to generate
            versions.Add("_thumb", "width=450&height=450&format=jpg&mode=max");

            string creditTrainigsFolder = Utils.ModuleCredits().TrainigsFolder;

            ImageJob im = new ImageJob(file, creditTrainigsFolder + "\\<guid>.<ext>", new ResizeSettings(versions["_thumb"]));
            im.CreateParentDirectory = true; //Auto-create the uploads directory.
            im.Build();

            string[] fullPath = im.FinalPath.Split('\\');

            string finalSmallFullFileName = string.Empty;
            if (fullPath != null && fullPath.Length > 1)
            {
                finalSmallFullFileName = fullPath[fullPath.Length - 1];
            }

            trainingPhotoImage.ImageUrl = creditTrainigsFolder + "/" + finalSmallFullFileName;
        }
    }

}